import * as Cesium from 'cesium'
import * as THREE from 'three'

export class SyncCesiumWithThree {
    static instance = null
    static map = new Map()
    constructor({ cesiumCamera, threeCamera }) {
        this.cesiumCamera = cesiumCamera
        this.threeCamera = threeCamera
    }
    syncFrustum() {
        // todo
    }

    // todo 这种方接接近地面角度会发黑， 80-90度，
    syncPdu() {
        const positionWC = this.threeCamera
            .getWorldPosition(new THREE.Vector3())
            .toArray()
        const directionWc = this.threeCamera
            .getWorldDirection(new THREE.Vector3())
            .toArray()
        const upWc = this.threeCamera
            .localToWorld(new THREE.Vector3(0, 1, 0))
            .toArray()

        const camera = this.cesiumCamera
        camera.position = new Cesium.Cartesian3(...positionWC)
        camera.direction = new Cesium.Cartesian3(...directionWc)
        camera.up = new Cesium.Cartesian3(...upWc)
    }

    sync() {
        this.syncBySetView()
        this.syncFrustum()
    }

    syncBySetView() {
        const positionWC = this.threeCamera
            .getWorldPosition(new THREE.Vector3())
            .toArray()
        const directionWc = this.threeCamera
            .getWorldDirection(new THREE.Vector3())
            .toArray()
        const upWc = this.threeCamera
            .localToWorld(new THREE.Vector3(0, 1, 0))
            .toArray()

        this.cesiumCamera.setView({
            destination: new Cesium.Cartesian3(...positionWC),
            orientation: {
                direction: new Cesium.Cartesian3(...directionWc),
                up: new Cesium.Cartesian3(...upWc),
            },
        })
    }
}
